package com.zipou.myMail;

import java.io.IOException;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MyMailMessage extends MimeMessage {

	private String html;
	
	public MyMailMessage(Session session) {
		super(session);
	}

	public final void addAttachement(DataSource source, String filename) throws MyMailServiceException {
		try {
			BodyPart messageBodyPart = new MimeBodyPart();
			Multipart multipart = (MimeMultipart) getContent();

			// Part two is attachment
			messageBodyPart = new MimeBodyPart();
			messageBodyPart.setDataHandler(new DataHandler(source));
			messageBodyPart.setFileName(filename);
			multipart.addBodyPart(messageBodyPart);
			setContent(multipart);
		} catch (MessagingException e) {
			throw new MyMailServiceException("Failed to add an Attachements: " + e.getMessage());
		} catch (IOException e) {
			throw new MyMailServiceException("IO Exception: " + e.getMessage());
		}
	}

	public final void addDest(String dest) throws AddressException, MessagingException {
		this.addRecipient(Message.RecipientType.TO, new InternetAddress(dest));
	}

	public final String getHtml() {
		return html;
	}

	public final void setHtml(String html) {
		try {
			Multipart multipart = new MimeMultipart();

			// Create the message part 
			BodyPart messageBodyPart = new MimeBodyPart();

			// Fill the message
			//		messageBodyPart.setText(html);
			messageBodyPart.setContent(html, "text/html");

			multipart.addBodyPart(messageBodyPart);

			// Put parts in message
			setContent(multipart);
			this.html = html;
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	
	
	
}
